package org.gthelper.data.client;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.gthelper.error.ErrorCode;

public class DataGeter
{
	public final int lengthperread=8192;
	public long getData(DataInputStream dis,OutputStream output)
	{
		try{
	
			//get data size
			long datalength = 0;
			byte[] lengthtmp1 = new byte[8];
			byte[] lengthtmp2 = new byte[8];
			int lwant=8;
			long readed=0;
			int readnow=0;
			long lastTime = System.currentTimeMillis();
			//获得前八个
loopdatal:	while(true)
			{
				while((readnow=dis.read(lengthtmp1,0,lwant))>0)
				{
					lwant=(int)(lwant-readnow);
					for(int i=0;i<readnow;i++)
					{
						lengthtmp2[(int)(readed+i)]=lengthtmp1[i];
					}
					readed=readnow+readed;
					if(lwant<1)break loopdatal;
				}
				if((System.currentTimeMillis()-lastTime)>50)break;
			}
			
			//转为long
			for(int i=0;i<8;i++)
			{
				if(lengthtmp2[i]!='\0')
				{
					long tmp = 0x00000000000000ff&lengthtmp2[i];
					tmp = tmp << (8*(7-i));
					datalength = datalength+tmp;
				}
			}
			if(datalength<=0)return ErrorCode.WRONGFORM;
			if(datalength>=ErrorCode.ERRBASE)return datalength;
			
			lastTime = System.currentTimeMillis();
			
			//get data
			readed=0;
			int want=lengthperread;
			if(want>datalength)want=(int)datalength;
			byte[] btmp = new byte[want];
			lastTime = System.currentTimeMillis();
loopdata:	while(true)
			{
				while((readed=dis.read(btmp,0,want))>0)
				{
					datalength=datalength-readed;
					output.write(btmp,0,(int)readed);
					if(datalength<1)break loopdata;
					if(datalength<want)want=(int)datalength;
					lastTime = System.currentTimeMillis();
					System.out.println(readed);
				}
				if((System.currentTimeMillis()-lastTime)>50)break;
			}
			if(datalength!=0)return ErrorCode.WRONGFORM;
			
		}catch(IOException e)
		{
			return ErrorCode.IOEXC;
		}
		return ErrorCode.NORMAL;
	}
	
	
	
}